package com.m4f.fse.components;

import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Map;
import java.util.SortedSet;
import java.util.logging.Logger;
import com.m4f.fse.components.fitters.ifc.Fitter;
import com.m4f.fse.components.ifc.SearchEngine;
import com.m4f.fse.components.mergers.ifc.Merger;
import com.m4f.fse.utils.StackTraceUtil;

public class SearchStack {
	
	private SortedSet<SearchEngine> stack = new TreeSet<SearchEngine>();
	private Merger merger;
	private Fitter fitter;
	private static final Logger LOGGER = Logger.getLogger(SearchStack.class.getName());
	
	public SearchStack(Merger m, Fitter f) {
		this.merger = m;
		this.fitter = f;
	}
	
	public void addEngine(SearchEngine engine) {
		this.stack.add(engine);	
	}
	
	public  byte[] search(Map<String, String> params) throws Exception {
		SortedMap<SearchEngine, byte[]> contentsMap = new TreeMap<SearchEngine, byte[]>();
		for (Iterator<SearchEngine> it = this.stack.iterator(); it.hasNext(); ) {
			SearchEngine engine = it.next();
			try {
				if(engine.isAcceptable(params)) {
					contentsMap.put(engine, engine.search(params));
				}
			} catch(Exception e) {
				LOGGER.severe(StackTraceUtil.getStackTrace(e));
			}
		}
		return this.fitter.fit(this.merger.merge(contentsMap), params).toByteArray();
	}
	
	
	
}